Actually, it just slices. In this recipe we investigate a new way to extract strings from other strings.Discussion
You're already familiar with String.substr(), which extracts a substring from a string using a starting index and a number of characters to take. JavaScript 1.2 introduces String.slice(), which takes a starting index, and an ending index as a way of specifying a substring to return.The rules for the beginning index and ending index are more complicated than for String.substr(). Given that:
startSlice is the zero-based position at which to begin slicing, and
stopSlice is the zero-based position at which to end slicing,
the following rules apply:
- slice extracts up to but not including stopSlice. string.slice(1,8) extracts the second character through the eighth character (characters indexed 1 through 7).
For our sample string, that would yield ''- When used as a negative index, stopSlice indicates an offset from the end of the string. string.slice(4,-1) extracts the fifth character through the second-to-last character in the string.
For our sample string, that would yield ''- If you omit stopSlice completely, slice() just extracts to the end of the string. Suppose we did that to our sample string, with 12 as the single argument:
string.slice(12) yields ''Go back to the top of the page, play around with the form, and see what results this new function gives you.
Copyright ©2000 by Charles River Media, All Rights Reserved